package com.heima.schedule.redis.impl;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class UpdateLocakTimeoutTask implements  Runnable{

    private StringRedisTemplate stringRedisTemplate;
    private String uuid;
    private Long timeout;
    private TimeUnit unit;
    private String key;

    public UpdateLocakTimeoutTask(StringRedisTemplate stringRedisTemplate,String uuid,Long timeout,TimeUnit unit,String key){
        this.stringRedisTemplate=stringRedisTemplate;
        this.uuid=uuid;
        this.timeout=timeout;
        this.unit=unit;
        this.key=key;

    }


    @Override
    public void run() {
        try {
            while(!Thread.currentThread().isInterrupted()){
                //设置某一个key的过期时间
                //获取续命线程id
                long threadId = Thread.currentThread().getId();
                //将续命线程id和分布式锁进行关联
                stringRedisTemplate.opsForValue().set(uuid,threadId+"",timeout,unit);

                //重新设置分布式过期时间
                stringRedisTemplate.expire(key,timeout,unit);
                Thread.sleep(unit.toMillis(timeout)*2/3);
            }
        } catch (InterruptedException e) {
            throw  new RuntimeException(e);
        }
    }
}
